package com.qx.chat.akka;

import com.qx.chat.akka.actor.DeadLetterListener;
import com.qx.chat.akka.actor.SessionActor;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.DeadLetter;
import akka.actor.Props;

/**
 * 系统上下文，存放一些单例对象
 * @author cyf
 *
 */
public class Qxchat {

	private static Qxchat instance = new Qxchat();

	private ActorSystem actorSystem;

	private ActorRef sessionActor;

	public static Qxchat getInstance() {
		return instance;
	}

	private Qxchat() {
	}

	public ActorSystem getAkkaSystem() {
		return actorSystem;
	}

	/**
	 * 初始化
	 * @param actorSystem
	 */
	public void setAkkaSystem(ActorSystem actorSystem) {
		//创建sessionActor
		this.sessionActor = actorSystem.actorOf(
				Props.create(SessionActor.class), SessionActor.ACTOR_ID);
		//创建无响应消息处理actor
		ActorRef deadLetter = actorSystem.actorOf(Props.create(DeadLetterListener.class), "dead");
		actorSystem.eventStream().subscribe(deadLetter, DeadLetter.class);
		this.actorSystem = actorSystem;
	}

	public ActorRef getSessionActor() {
		return sessionActor;
	}

	/**
	 * 通过登录名获取用户对应的actor
	 * @param loginName
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public ActorRef getActorByLoginName(String loginName) {
		return actorSystem.actorFor("akka://"+AkkaSystem.DEFAULT_SYSTEM_NAME+"/user/"+SessionActor.ACTOR_ID+"/"+loginName);
	}
}
